package com.opener.common.encrypt;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

/**
 * @author baboy
 */
public class AesUtils {
	static final String KEY_ALGORITHM = "AES";
	static final String CIPHER_ALGORITHM_ECB = "AES/ECB/PKCS5Padding";
	static final String CIPHER_ALGORITHM_CBC = "AES/CBC/PKCS5Padding";
	private static int DEF_SEC_BITS = 128;

	public static String encryptString(String c, String pwd){
		return Hex.encodeHexString(encrypt(c, pwd));
	}
	public static byte[] encrypt(String c, String pwd){
		try {
			return encrypt(c.getBytes("UTF-8"), pwd);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	public static byte[] encrypt(byte[] c, String pwd) {
		try {
			byte[] keyBytes = Arrays.copyOf(pwd.getBytes("UTF-8"), 16);
			SecretKey key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);

			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] cleartext = c;
			byte[] ciphertextBytes = cipher.doFinal(cleartext);
			return ciphertextBytes;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	public static String decryptString(String c, String pwd){
		return new String(decrypt(c, pwd));
	}
	public static byte[] decrypt(String c, String pwd) {
		try {
			byte[] b = Hex.decodeHex(c.toCharArray());
			return decrypt(b, pwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] decrypt(byte[] c, String pwd) {
		try {
			byte[] keyBytes = Arrays.copyOf(pwd.getBytes("UTF-8"), 16);
			SecretKey key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
			Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_ECB);
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] cleartext = c;
			byte[] ciphertextBytes = cipher.doFinal(cleartext);
			return ciphertextBytes;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	public static void main(String[] args){
		String s = "7GRK7J2";
		s = DigestUtils.md5Hex(s);
		s = DigestUtils.sha1Hex(s);
		s = AesUtils.encryptString(s,s);
		System.out.println(s);
		String pwd = "123";
		String txt = "1234567890";
		byte[] b = encrypt(txt,pwd);
		String c = Hex.encodeHexString(b);
		System.out.println(c);
		c = new String(decrypt(c,pwd));
		System.out.println(c);

		c = encryptString(txt,pwd);
		System.out.println(c);
		c = decryptString(c,pwd);
		System.out.println(c);
		pwd = DigestUtils.sha1Hex(pwd).substring(0,16);
		c = encryptString(txt,pwd);
		System.out.println(c);
		System.out.println(decryptString(c,pwd));
	}
}
